﻿using Microsoft.AspNetCore.DataProtection.Repositories;
using ServiceStack.Redis;
using Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace vueweb
{
	public class RedisXmlRepository : IXmlRepository
	{
		private readonly RedisClientsManagerWrap _manager;
		private readonly string _key;
		private BinarySerializer serializer = new BinarySerializer();

		public RedisXmlRepository(RedisClientsManagerWrap managerWrap, string key)
		{			
			_manager = managerWrap;
			_key = key;
		}
		
		public IReadOnlyCollection<XElement> GetAllElements()
		{
			return this.GetAllElementsCore().ToList().AsReadOnly();
		}

		private IEnumerable<XElement> GetAllElementsCore()
		{
			using (var clientM = _manager.Get())
			{
				using (var redis = clientM.GetReadOnlyClient() as IRedisNativeClient)
				{
					byte[][] bufs = redis.LRange(_key, 0, -1);
					foreach (byte[] buf in bufs)
					{
						string strv = (string)serializer.Deserialize(buf);
						string aes = MyAES.Decode(strv);
						XElement elem = XElement.Parse(aes);
						yield return elem;
					}
				}
			}
		}
		
		public void StoreElement(XElement element, string friendlyName)
		{
			using (var clientM = _manager.Get())
			{
				using (var redis = clientM.GetReadOnlyClient() as IRedisNativeClient)
				{
					string strv = element.ToString();
					string aes = MyAES.Encode(strv);
					byte[] buf = serializer.Serialize(aes);
					redis.RPush(_key, buf);
				}
			}
		}
	}
}
